package org.stvd.repository.workflow.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.stvd.core.dto.QueryResult;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.workflow.WfUser;
import org.stvd.repository.base.impl.BaseDaoImpl;
import org.stvd.repository.workflow.WfUserDao;

@Repository("WfUserDao")
public class WfUserDaoImpl extends BaseDaoImpl<WfUser> implements WfUserDao {

    @Override
    public QueryResult<Map<String,Object>> wfUserQuery(Integer start, Integer limit, String groupCode, String createUid) {
        String sql = "SELECT t1.*, t2.name FROM wf_user t1 LEFT JOIN wf_group t2 "
                + " ON t1.group_code = t2.code WHERE t1.create_uid = :createUid"
                + " AND (t1.group_code = :groupCode or '' = :groupCode) "
                + " ORDER BY t1.create_time DESC";
        Map<String,Object> param = new HashMap<>();
        param.put("createUid", createUid);
        param.put("groupCode", groupCode);
        return getQueryResultBySQLToMap(start, limit, sql, param);
    }

    @Override
    public List<WfUser> listWfUserByCode(String groupCode) {
        String hql = "FROM WfUser where groupCode = ?0";
        return findByHQL(hql, groupCode);
    }
    
    @Override
    public  WfUser getWfUserByUid(String uid) {
         List<WfUser> list = findByHQL("FROM WfUser WHERE userId = ?0 ", uid);
         if(list!=null && list.size() > 0){
             return list.get(0);
         }
         return null;
         
    }
    
    @Override
    @Transactional
    public int deleteWfUserByCode(String groupCode) {
        String hql = "delete FROM WfUser where groupCode = :groupCode";
        return em.createQuery(hql).setParameter("groupCode", groupCode).executeUpdate();
    }
    
    @Override
    public QueryResult<Map<String,Object>> wfUserQueryResultByName(Integer start, Integer limit, String uName, String createUid) {
        String sql = "SELECT t1.*, t2.name FROM wf_user t1 LEFT JOIN wf_group t2 "
                + " ON t1.group_code = t2.code WHERE 1=1 ";
        Map<String,Object> param = new HashMap<>();
        if(!StringUtil.isEmpty(uName)) {
        	sql=sql+" AND (t1.user_name like :uName) ";
        	param.put("uName", "%"+uName+"%");
        }
        if(!StringUtil.isEmpty(createUid)) {
        	sql=sql+" AND (t1.create_uid = :createUid) ";
        	param.put("createUid", createUid);
        }
        return getQueryResultBySQLToMap(start, limit, sql, param);
    }
}
